#!/usr/bin/env python3
# _*_ coding:utf-8 _*_


from django.shortcuts import render, redirect, HttpResponse
from rbac import models
from rbac.forms.Icon import IconModelForm
from Arc.utils.GetData import getpage


def icon_list(request):
    """
    角色列表
    :param request:
    :return:
    """
    icon_queryset = models.Icon.objects.all()
    pager, data_list = getpage(request, icon_queryset)
    return render(request, 'rbac/icon_list.html', {'icons': data_list, 'pager': pager})


def icon_add(request):
    if request.method == 'POST':
        forms = IconModelForm(request.POST)
        if forms.is_valid():
            forms.save()

            return redirect('rbac:icons')
    elif request.method == 'GET':
        forms = IconModelForm()
    else:
        forms = IconModelForm()

    return render(request, 'rbac/form_temp.html', {'forms': forms})


def icon_edit(request, pk):
    obj = models.Icon.objects.filter(id=pk).first()
    if not obj:
        return render(request, '404.html', {'error': '查看页面不存在！'})
    if request.method == 'GET':
        forms = IconModelForm(instance=obj)
        return render(request, 'rbac/form_temp.html', {'forms': forms})
    forms = IconModelForm(instance=obj, data=request.POST)
    if forms.is_valid():
        forms.save()
        return redirect('rbac:icons')
    else:
        return render(request, 'rbac/form_temp.html', {'forms': forms})


def icon_del(request, pk):
    if request.method == 'POST':
        if pk == request.POST.get('pk') and request.POST.get('csrfmiddlewaretoken'):
            models.Icon.objects.filter(id=pk).delete()
            return HttpResponse('200')
    else:
        return render(request, '403.html')
